package com.kitty.game.newchoujiang.service;

import com.kitty.common.cache.RedisService;
import com.kitty.common.cache.entity.ActivityNumberSet;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.config.NPC;
import com.kitty.game.drop.newservice.NewDropService;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.ChargeData;
import com.kitty.game.equip.model.RoleData;
import com.kitty.game.newchoujiang.SendPopMessage;
import com.kitty.game.newchoujiang.entity.ChouJiangInfo;
import com.kitty.game.npc.service.NewNpcService;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.titleManage.service.TitleInfoService;
import com.kitty.game.utils.*;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import com.kitty.common.utils.DecodeSendMessage;
import com.kitty.game.reward.service.RewardSetService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class NewChouJiangService {
    private static int once = 100000;
    private static int tenTimes = 888888;
    private static String chouJiangType = "";
    private static int minLevel = 0;
    private static int minRechare = 0;
    private static  Map<Integer, List<ChouJiangInfo>> rewardInfoMap = new HashMap<>();
    private static  List<Integer> rewardSetList = new ArrayList<>();
    private static String finalstartTime = "";
    private static String finalendTime = "";
    @Autowired
    RedisService redisService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private NewNpcService newNpcService;
    @Autowired
    ServerService serverService;
    @Autowired

    NewDropService newDropService;
    int neice;
    public void load(){
        getChouJiangInfo();
    }

    private void getChouJiangInfo(){
        rewardSetList = new ArrayList<>();
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        int reward0 = Integer.parseInt(DataCache.REDIS_DATA.get("choujiang_set_0").toString());
        int reward1 = Integer.parseInt(DataCache.REDIS_DATA.get("choujiang_set_1").toString());
        int reward2 = Integer.parseInt(DataCache.REDIS_DATA.get("choujiang_set_2").toString());
        int reward3 = Integer.parseInt(DataCache.REDIS_DATA.get("choujiang_set_3").toString());
        int reward4 = Integer.parseInt(DataCache.REDIS_DATA.get("choujiang_set_4").toString());
        rewardSetList.add(reward4);
        rewardSetList.add(reward3);
        rewardSetList.add(reward2);
        rewardSetList.add(reward1);
        rewardSetList.add(reward0);
        Dao dao = SpringUtils.getBean(Dao.class);
        List<ChouJiangInfo> list = dao.query(ChouJiangInfo.class, Cnd.NEW());
        Map<Integer, List<ChouJiangInfo>> loadChouJiangSer = new HashMap<>();
        for (ChouJiangInfo chouJiangInfo : list) {
            List<ChouJiangInfo> infos = loadChouJiangSer.computeIfAbsent(chouJiangInfo.getRewardlevel(), k -> new ArrayList<>());
            infos.add(chouJiangInfo);
        }
        NewChouJiangService.rewardInfoMap = loadChouJiangSer;
        once = Integer.parseInt(DataCache.REDIS_DATA.get("choujiangyici").toString());
        tenTimes  =Integer.parseInt(DataCache.REDIS_DATA.get("choujiangshici").toString());
        chouJiangType = DataCache.REDIS_DATA.get("choujiang_type");
        minLevel = Integer.parseInt(DataCache.REDIS_DATA.get("choujiang_min_level"));
        minRechare = Integer.parseInt(DataCache.REDIS_DATA.get("choujiang_min_rechar"));
    }

    public synchronized void npcButton(Role role, String msg, NPC npc) {
        if (StringUtils.isBlank(msg)) {
            return;
        }
        int count = 0;
        int number = 0;
        if ("抽奖一次".equals(msg)) {
            number = once;
            count = 1;
        }else if ("抽奖十次".equals(msg)) {
            number = tenTimes;
            count = 10;
        }else if ("抽奖排名".equals(msg)) {
            String reward = "";
            for (int i = 0; i < 3; i++) {
                String r1 = DataCache.REDIS_DATA.get("choujiang_rank_reward" + (i+1)).toString();
                String showName = "";
                for (String s : r1.split("\\+")) {
                    HashMap<String, Object> stringObjectHashMap = DecodeSendMessage.buildSendRewardMessage(s);
                    showName += stringObjectHashMap.get("showName").toString()+",";
                }
                if(showName.contains(",")){
                    showName = showName.substring(0,showName.length() -1);
                }
                reward += "  第"+(i+1)+"名：#R"+showName+"#n\n";
            }
            String rankNames = "";
            List<String> choujiangrankList = redisService.getRankList("choujiangrank");
            for (int i = 0; i < 3; i++) {
                String s = "";
                int score = 0;
                try{
                    s = choujiangrankList.get(i);
                    score = redisService.findScore("choujiangrank", s);
                }catch(Exception e){
                    s  = "虚位以待";
                }
                if("虚位以待".equals(s)){
                    rankNames += "  第"+(i+1)+"名：#G"+s+"#n\n";
                }else{
                    rankNames += "  第"+(i+1)+"名：#Y"+s+"#n    抽奖：#R "+score+"#n\n";
                }
            }
            String currentRank;
            int choujiangrank = redisService.find("choujiangrank", role.getName());
            if (choujiangrank == 0) {
                currentRank="# 当前没上榜，请道友再接再厉";
            } else {
                currentRank="# 当前排名：#R" +choujiangrank + "#n";
            }
            String state = redisService.get("choujiang_rank_state").toString();
            String nowDate = "";
            if ("1".equals(state)) {
                nowDate = finalstartTime+"  -  "+finalendTime;
            }else{
                nowDate = "未开始";
            }
            SendPopMessage respGeneralNotify = new SendPopMessage();
            String message = "AltarCeremonyRuleDlg|"+nowDate+"|"+reward+"|"+rankNames+"|"+currentRank;
            respGeneralNotify.setName(message);
            respGeneralNotify.setType((byte)2);
            MessagePusher.pushMessage(role, respGeneralNotify);

            //newNpcService.sendNpcContent(role, npc, getShow(role));
            return;
        }
        if(ServerService.neice!=100){
            if (role.getTotalCharge() <= minRechare && role.getLevel() < minLevel){
                MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有充值或等级不足，不能抽奖！！"));
                return;
            }
        }
        if (serverService.getServer().getId() == 10000){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服专线，不能抽奖！！"));
            return;
        }

        //减少
        roleService.subCountByteType(role, number,chouJiangType);
        //抽奖
        for (int i = 0; i < count; i++) {
            getOnce(role);
            //增加抽奖次数，用于发送抽奖次数奖励
            changeChouJiangNum(role,1);
        }
        //增加抽奖记录   用于抽奖排行榜
        addChoujiangRankCount(role, count);
    }

    /**
     * 获取抽中的奖品 等级
     */
    public Integer getRandom(int luckyValue) {
        int total = 0;
        for (Integer integer : rewardSetList) {
            total += integer;
        }
        //幸运值玩法
        int result = ThreadLocalRandom.current().nextInt(total) + 1 + luckyValue;
        int temp = 0;
        for (Integer integer : rewardSetList) {
            temp += integer;
            if (result <= temp) {
                return rewardSetList.size()-1-rewardSetList.indexOf(integer);
            }
        }
        return null;
    }
    //抽一次
    public void getOnce(Role role) {
        //增加幸运值，若未抽中特等奖或者一等奖，幸运值加1
        int luckyValue = role.getExtendBox().getLuckyValue()==null?0:role.getExtendBox().getLuckyValue();
        int gift = getRandom(luckyValue);
        if(gift<=1){
            luckyValue = 0;
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("抽中大奖，幸运值归零！当前幸运值#R"+luckyValue+"#n"));
        }else{
            luckyValue+=1;
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("当前幸运值#R"+luckyValue+"#n,幸运值越高获得大奖几率越大！"));
        }
        role.getExtendBox().setLuckyValue(luckyValue);
        if(!rewardInfoMap.containsKey(gift)){
            return ;
        }
        List<ChouJiangInfo> chouJiangInfos = rewardInfoMap.get(gift);
        int result = ThreadLocalRandom.current().nextInt(chouJiangInfos.size());
        ChouJiangInfo chouJiangInfo = chouJiangInfos.get(result);
        String remark = chouJiangInfo.getRemark();
        String[] remarks = remark.split("\\+");
        for (String s : remarks) {
            newDropService.addRewardTask(role,s,chouJiangInfo.getNotice());
        }

    }
    public void changeChouJiangNum(Role role,Integer num){
        int oldNum = role.getExtendBox().getChoujiangNum()==null?0:role.getExtendBox().getChoujiangNum();
        int newNum = oldNum += num;
        //发送称号
        Map<Integer, String> choujiangMapByGroup = TitleInfoService.choujiangMapByGroup;
        if(choujiangMapByGroup.containsKey(newNum)){
            String s = choujiangMapByGroup.get(newNum);
            TitleInfo titleInfo = new TitleInfo();
            titleInfo.setType(s);
            titleInfo.setTitle(s);
            SpringUtils.getRoleService().addTitle(role, titleInfo);
        }
        //发放物品
        Map<Integer, ActivityNumberSet.RewardSet> rewardMapByChouJiang = RewardSetService.rewardMapByChouJiang;
        if(rewardMapByChouJiang.containsKey(newNum)){
            ActivityNumberSet.RewardSet rewardSet = rewardMapByChouJiang.get(newNum);
            newDropService.addRewardTask(role,rewardSet.getRemake(),rewardSet.getBeizhu());
        }
        //choujiangNumReward(role,newNum);
        role.getExtendBox().setChoujiangNum(newNum);
    }
    private static final String NOTICE_CONTENT = "抽奖排行榜活动开始了，时间：%s-%s,活动结束后前三名将获得丰厚的奖励！";
    /*
    开启抽奖排行榜
     */
    public void startChouJiangRank(String startTime,String endTime){
        redisService.set("choujiang_rank_state","1");
        finalstartTime = startTime;
        finalendTime = endTime;
        String notice = String.format(NOTICE_CONTENT, startTime,endTime);
        SpringUtils.getChatService().sendSystem(notice, Const.BRODCAST_MSG_TYPE_ROLE);
        //String choujiang_rank = redisService.get("choujiang_rank").toString();
        //重置抽奖次数记录信息
        ChargeData chargeData = new ChargeData();
        chargeData.setTime(System.currentTimeMillis());
        String s = Json.toJson(chargeData);
        redisService.set("choujiang_rank",s);
        //清空排行榜信息
        redisService.delAllRank("choujiangrank");
    }
    public void rebootChoujiangRank(String startTime,String endTime){
        finalstartTime = startTime;
        finalendTime = endTime;
    }
    /*
   关闭抽奖排行榜
    */
    public void endChouJiangRank(){
        log.info("抽奖排行榜结束，正在结算奖励。");
        String state = redisService.get("choujiang_rank_state").toString();
        if("1".equals(state)){
            redisService.set("choujiang_rank_state","0");
            //发送奖励
            try{
                sendChouJiangRankReward();
            }catch(Exception e){
                log.info("发送抽奖排行榜奖励出错：",e);
            }finally {
                ChargeData chargeData = new ChargeData();
                chargeData.setTime(System.currentTimeMillis());
                String s = Json.toJson(chargeData);
                redisService.set("choujiang_rank",s);
                //清空排行榜信息
                redisService.delAllRank("choujiangrank");
            }
        }
    }
    //增加抽奖排行榜开启期间人的抽奖次数
    public void addChoujiangRankCount(Role role, int count) {
        String state = redisService.get("choujiang_rank_state").toString();
        if ("1".equals(state)) {
            String content = redisService.get("choujiang_rank").toString();
            ChargeData chargeData = Json.fromJson(ChargeData.class, content);
            String curr = DateUtils.formatDate(new Date());
            RoleData roleData = new RoleData();
            if(chargeData.getHashMap() == null){
                chargeData.setHashMap(new HashMap<>());
            }
            if( chargeData.getHashMap().containsKey(role.getUid())){
                roleData = chargeData.getHashMap().get(role.getUid());
                roleData.setCharge(count + roleData.getCharge());
            }else{
                roleData.setCharge(count);
                roleData.setName(role.getName());
                roleData.setUid(role.getUid());
                chargeData.getHashMap().put(role.getUid(), roleData);
            }
            redisService.add("choujiangrank",role.getName(),(double)roleData.getCharge());
            String s = Json.toJson(chargeData);
            redisService.set("choujiang_rank",s);
        }
    }

    //查看抽奖排行榜
    public String getShow(Role role) {
        String state = redisService.get("choujiang_rank_state").toString();
        if (!"1".equals(state)) {
            return "当前没有抽奖排行榜活动 [离开]";
        }
        StringBuilder stringBuilder = new StringBuilder("抽奖次数排名奖励，活动结束自动发放。");
        int choujiangrank = redisService.find("choujiangrank", role.getName());
        if (choujiangrank == 0) {
            stringBuilder.append("#R当前没上榜，请道友再接再厉#n");
        } else {
            stringBuilder.append("当前第#R" +choujiangrank + "#n名");
        }
        stringBuilder.append("[离开]");
        return stringBuilder.toString();
    }


    //抽奖排行榜结算奖励
    public void sendChouJiangRankReward(){
        List<String> names = redisService.getRankList("choujiangrank");
        for (int i = 0; i < 3; i++) {
            if(names.size()>i){
                Role role = SpringUtils.getRoleService().getPlayerBy(names.get(i));
                String reward = redisService.get("choujiang_rank_reward" + (i+1)).toString();
                if(StringUtils.isNotEmpty(reward)){
                    String showName = "";
                    for (String s : reward.split("\\+")) {
                        HashMap<String, Object> stringObjectHashMap = DecodeSendMessage.buildSendRewardMessage(s);
                        showName += stringObjectHashMap.get("showName").toString()+",";
                        newDropService.addRewardTask(role,s,"");
                    }
                    if(showName.contains(",")){
                        showName = showName.substring(0,showName.length() -1);
                    }
                    String msg = "恭喜#Y" + role.getName() + "#n在献花抽奖排行榜活动中获得第#R" + (i+1) +"#n名，获得#Y"+showName+"#n奖励！";
                    SpringUtils.getChatService().sendAdnotice(msg);
                }
            }
        }
    }



    public static void main(String[] args) {
        final String NOTICE_CONTENT = "献花抽奖排行榜活动开始了，时间：%s-%s,活动结束后前三名将获得丰厚的奖励！";
        String notice = String.format(NOTICE_CONTENT, 1,2);
        System.out.println(notice);
    }
}
